package com.springboot.service.impl;

import com.springboot.pojo.User;
import com.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gali
 * @description:自定义拦截用户权限
 * @date 2022/6/22 14:50
 */
@Component
public class UserDetailSecurityImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User userInfo = userService.getUserInfo(s);
        if (userInfo==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        String role = userInfo.getRole();
        List<GrantedAuthority> grantedAuthorities =new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role));
        passwordEncoder.encode(userInfo.getPassword());
        return  new org.springframework.security.core.userdetails.User(
                userInfo.getUsername(),
                userInfo.getPassword(),
                grantedAuthorities
        );
    }
}
